import React, { Component, PureComponent } from 'react';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import IotDeviceForm from '@/components/IotDeviceForm';
import { Card, Divider, Button, Icon, Modal,Form } from 'antd';
import AdvancedSearch from '@/components/AdvancedSearch';
import AdvancedTable from '@/components/AdvancedTable';
import IotDeviceFind from '@/components/IotDeviceFind';
import styles from './equipment.less';
import { deleteById, retrieval} from '@/services/requestData';
import { openNotificationWithIcon, switcher } from '@/utils/tools';

/**
 * 设备列表
 * @author LongTeng 2019-04-19
 */
@connect(({ device_add, loading }) => ({
  device_add,
  loading: loading.effects['models/device/device_add'],
}))
export default class Equipment extends Component {
  constructor(props) {
    super(props);
    this.state = {
      datalines: [],
      loading: false,
      visible: false,
      visibleFind:false,
      row: {},

      columnTypeKey:[],
      columnTypeValue:[],
      columnGroupKey:[],
      columnGroupValue:[],
    };
    // 高级检索配置
    this.master = 'device';
    this.items = [
      {  key: 'id',  name: '设备ID',  type: 'input',  first: true,  datatable: this.master,  mode: 3,},
      {  key: 'device_name',  name: '设备名称',  type: 'input',  first: true,  datatable: this.master,  mode: 3,},
      {  key: 'fk_device_type_id',  name: '设备类型',  type: 'combo',  first: false,  datatable: this.master,  mode: 3,async:
      retrieval({datatable:"devicetype",conds:[]}).then(res=>{
        let dicType = {};
        res.forEach(x=>{
          dicType[x.device_type_name]=x.id;
        })
          return dicType;
      }).catch(e=>{
        openNotificationWithIcon("error","下拉列表读取失败","数据读取失败，请确认网络连接是否正常");
      })
    },
      {  key: 'fk_device_group_id',  name: '设备类型',  type: 'combo',  first: false,  datatable: this.master,  mode: 3,async:
      retrieval({datatable:"devicegroup",conds:[]}).then(res=>{
        let dicGroup = {};
        res.forEach(x=>{
          dicGroup[x.device_group_name]=x.id;
        })
        return dicGroup;
      }).catch(e=>{
        openNotificationWithIcon("error","下拉列表读取失败","数据读取失败，请确认网络连接是否正常");
      })
    },
    ];
    // 表格栏目对应字段配置
    this.columns = [
      { title: '设备ID', dataIndex: 'id', sorter: true, first: true },
      { title: '设备名称', dataIndex: 'device_name', sorter: true, first: true },
      { title: '设备类型', dataIndex: 'fk_device_type_id', sorter: true, first: true , render: (val) => {
        return switcher(val, this.state.columnTypeKey, this.state.columnTypeValue, "类型不存在");
      } },
      { title: '设备组', dataIndex: 'fk_device_group_id', sorter: true, first: true , render: (val) => {
        return switcher(val, this.state.columnGroupKey, this.state.columnGroupValue, "组不存在");
      } },
      { title: '操作', dataIndex: '$$operations', render: (row) => {
        return (<div>
          <Button className={styles.buttonFind} onClick={() => {
              console.log(row);
              this.setState({
                  row:row,
                  visibleFind: true,
              });
          }}>查看订阅</Button>
          <Button className={styles.buttonCheck} onClick={() => {
              console.log(row);
              this.setState({
                  row:row,
                  visible: true,
                  disabled:true,
              });
          }}>查看</Button>
          <Button className={styles.buttonEdit} onClick={() => {
              let handle = row.getHandle();
              this.setState({
                  row:row,
                  visible: true,
                  disabled:false,
                  handle:handle,
              });
              handle.updateList();
          }}>修改</Button>
          <Button className={styles.buttonDelete} onClick={() => {
              Modal.confirm({
                title: '删除',
                content: '确定要删除该数据吗？',
                onOk() {
                  let response = deleteById("Device",row.id);
                  response.then(content => {
                    openNotificationWithIcon("success","删除成功","恭喜，删除成功！");
                    let handle = row.getHandle();
                    handle.updateList();
                  }).catch(e=>{
                    openNotificationWithIcon("error","加载失败","无法获得数据，请检查信息是否正确");
                  });
                },
                onCancel() {},
              });
          }}>删除</Button>
          </div>);
      } },
    ];
    // 特殊控制按钮配置
    this.controllers = [
      {
        name: '添加',
        icon: 'file',
        callback: handle => {
          this.setState({
            row: {},
            visible: true,
            disabled: false,
            handle: handle,IotDeviceForm
          });
          handle.updateList();
        },
      },
    ];
  }
  
  //默认render结束后，从数据库获取数据，替换表格中显示的id，默认显示对应id的中文名称
  componentDidMount(){
    let responseType = retrieval({datatable:"devicetype",conds:[]});
    responseType.then(res=>{
      let columnTypeKey=[];
      let columnTypeValue=[];
      res.forEach(x=>{
        columnTypeKey.push(x.id);
        columnTypeValue.push(x.device_type_name);
      })
      this.setState({
        columnTypeKey:columnTypeKey,
        columnTypeValue:columnTypeValue,
      })      
    }).catch(e=>{
      openNotificationWithIcon("error","数据读取失败","数据读取失败，请确认网络连接是否正常");
    })

    let responseGroup = retrieval({datatable:"devicegroup",conds:[]})
    responseGroup.then(res=>{
      let columnGroupKey=[];
      let columnGroupValue=[];
      res.forEach(x=>{
        columnGroupKey.push(x.id);
        columnGroupValue.push(x.device_group_name);
      })
      this.setState({
        columnGroupKey:columnGroupKey,
        columnGroupValue:columnGroupValue,
      })   
    }).catch(e=>{
      openNotificationWithIcon("error","数据读取失败","数据读取失败，请确认网络连接是否正常");
    })
  }

  //添加、修改功能的提交按钮事件
  handleSubmit = (err, values) => {
    const { dispatch } = this.props;
    if (!err) {
      let form = {};
      let objKeys = Object.keys(values);
      for(var one of objKeys){
        if(typeof values[one] == "object"){
          form[one] = values[one].key;
        }else{
          form[one] = values[one];
        }
      }
      form.id = this.state.row.id
      console.log(form);
      dispatch({
        type: 'device_add/addDevice',
        payload: {
          datatable: "Device",
          body: form,
        },
        callback:()=>{
          let handle = this.state.handle;
          handle && handle.updateList();
        }
      });
      this.setState({visible: false})
    }
  };

  //通过dva获取提交状态，提示是否提交成功
  showAlert = () => {
    const duration = 3.5;
    if (this.props.device_add.response) {
      let { state } = this.props.device_add.response;
      if (state) {
        openNotificationWithIcon("success","提交成功","恭喜，提交成功！");
      } else {
        openNotificationWithIcon("error","提交失败","请检查填写是否正确！");
      }
      this.props.device_add.response = null;
    }
  }

  //表单提交弹窗显示，弹出添加、编辑默认的表单
  showWindow = () => {
    const IotDeviceFormWrapper = Form.create({ name: 'IotDeviceForm' })(IotDeviceForm);
    this.showAlert();
    return (
      <Modal
        visible={this.state.visible}
        title="详细"
        width="800px"
        destroyOnClose
        onCancel={() => {
          this.setState({ visible: false });
        }}
        footer={null}
      >
        <div>
          <Card className={styles.selectCard}>
            <IotDeviceFormWrapper  onSubmit={this.handleSubmit}  disabled={this.state.disabled}  result={this.state.row}/>
          </Card>
        </div>
      </Modal>
    );
  };

  //订阅查看弹窗，显示该设备被哪些应用所订阅
  showSubFind = () => {
    return (
      <Modal
        visible={this.state.visibleFind}
        title="详细"
        width="1000px"
        destroyOnClose
        onCancel={() => {
          this.setState({ visibleFind: false });
        }}
        footer={null}
      >
        <div>
          <Card className={styles.selectCard}>
            <IotDeviceFind result={this.state.row} resEntity="subscriptiondevice"/>
          </Card>
        </div>
      </Modal>
    );
  };

  render() {
    return (
      <PageHeaderWrapper>
        {this.showWindow()}
        {this.showSubFind()}
        <Card bordered={true}>
          <AdvancedTable
            columns={this.columns}
            bordered
            // useMultiSelect
            updateFirst
            controllers={this.controllers}
            master={this.master}
            items={this.items}
          />
        </Card>
      </PageHeaderWrapper>
    );
  }
}
